package com.taptech.doufu.net.retrofit.file;

import android.app.Notification;
import android.app.NotificationManager;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.os.Build;
import android.os.Environment;
import android.os.IBinder;
import androidx.annotation.Nullable;
import androidx.core.app.NotificationManagerCompat;
import android.text.TextUtils;
import android.widget.Toast;

import com.taptech.doufu.R;
import com.taptech.doufu.app.WeMediaApplication;
import com.taptech.doufu.constant.Constant;
import com.taptech.doufu.util.UpdateUtil;
import com.taptech.doufu.util.ui.NotificationUtils;

import java.io.File;
import java.io.IOException;
import java.util.concurrent.TimeUnit;

import okhttp3.Interceptor;
import okhttp3.OkHttpClient;
import okhttp3.Response;
import okhttp3.ResponseBody;
import retrofit2.Call;
import retrofit2.Retrofit;
import retrofit2.http.GET;
import retrofit2.http.Url;

/**
 * Created by Wyatt on 2017/10/19/019.
 */

public class DownLoadApkService extends Service{

    private static String destFileDir = Environment.getExternalStorageDirectory()  + "/doufu";
    private static String destFileName = "doufu.apk";

    private Context mContext;
    private int preProgress;
    private int NOTIFI_ID = 1000;
    public static final String INTENT_KEY_APK_DOWNLOAD_URL = "apk_download_url";
    private Notification.Builder  builder;
    private NotificationManagerCompat notificationManagerCompat;
    private Retrofit.Builder retrofit;

    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        Toast.makeText(WeMediaApplication.applicationContext, "正在后台下载安装包，请耐心等待...", Toast.LENGTH_LONG).show();
        mContext = this;
        if (intent != null) {
            String url = intent.getStringExtra(INTENT_KEY_APK_DOWNLOAD_URL);
            if (!TextUtils.isEmpty(url)) {
                try {
                    loadFile(url);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
        return super.onStartCommand(intent, flags, startId);
    }


    /**
     * 下载文件
     */
    private void loadFile(String url){
        initNotification();
        if (retrofit == null) {
            retrofit = new Retrofit.Builder();
        }
        retrofit.baseUrl(Constant.BASE_URL)
                .client(initOkHttpClient())
                .build()
                .create(IFileLoad.class)
                .loadFile(url)
                .enqueue(new FileCallback(destFileDir,destFileName) {
                    @Override
                    public void onSuccess(File file) {
                        //安装软件
                        cancelNotification();
                        UpdateUtil.installApp(mContext,file);
                    }

                    @Override
                    public void onLoading(long curr, long total) {
                        updateNotification(curr*100/total);
                    }

                    @Override
                    public void onFailure(Call<ResponseBody> call, Throwable t) {
                        cancelNotification();
                    }
                });

    }


    public interface IFileLoad{
        @GET
        Call<ResponseBody> loadFile(@Url String url);
    }



    /**
     * 初始化OkHttp
     */
    private OkHttpClient initOkHttpClient() {
        OkHttpClient.Builder builder = new OkHttpClient.Builder();
        builder.connectTimeout(100000, TimeUnit.SECONDS);
        builder.networkInterceptors().add(new Interceptor() {
            @Override
            public Response intercept(Chain chain) throws IOException {
                Response originalResponse = chain.proceed(chain.request());
                return originalResponse
                        .newBuilder()
                        .body(new FileResponseBody(originalResponse))
                        .build();
            }
        });
        return builder.build();
    }



    private static final String channelId = "update";
    private static final String channelName = "Update";
    /**
     * 初始化Notification通知
     */
    public void initNotification() {
        //在通知栏中显示
        NotificationUtils.INSTANCE.createNotificationChannel(mContext,channelId,channelName,NotificationManager.IMPORTANCE_LOW);
        builder = new Notification.Builder(mContext)
                .setSmallIcon(R.drawable.new_icon)
                .setSubText("0%")
                .setContentTitle("豆花升级")
                .setProgress(100, 0,false);
        if (Build.VERSION.SDK_INT > Build.VERSION_CODES.O) {
            builder.setChannelId(channelId);
        }
        notificationManagerCompat = NotificationManagerCompat.from(mContext);
        notificationManagerCompat.notify(NOTIFI_ID, builder.build());
    }

    /**
     * 更新通知
     */
    public void updateNotification(long progress) {
        int currProgress = (int) progress;
        if (preProgress < currProgress) {
            builder.setSubText(progress + "%");
            builder.setProgress(100, (int) progress, false);
            notificationManagerCompat.notify(NOTIFI_ID, builder.build());
        }
        preProgress = (int) progress;
    }

    /**
     * 取消通知
     */
    public void cancelNotification() {
        notificationManagerCompat.cancel(NOTIFI_ID);
    }
}
